import  request  from '@/utils/request' 
import { setTokenInfo } from '@/utils/storage'
import { Dispatch } from 'redux'
import { LoginAction } from '../reducers/login'

// 验证码
export const sendCode = (mobile: string) => {
    return async () => {
        await request({
            url: `/sms/codes/${mobile}`,
            method: 'get'
        })
    }
}

/**
 * 
 * @param {*} data 
 * @returns 
 */

 type Token = {
    token: string
    refresh_token: string
  }

export const saveToken = (payload: Token): LoginAction => {
    return {
        type: 'login/token',
        payload
    }
}

/**
 * 登录功能
 * @param {*} data 
 * @returns 
 */

export const login = (data: { mobile: string; code: string }) => {
    return async (dispatch: Dispatch) => {
        const res = await request({
            method: 'post',
            url: '/authorizations',
            data,
        })
        // 保存token到redux中
        dispatch(saveToken(res.data))
        // 保存到本地
        setTokenInfo(res.data)
    }
}

/**
 * 退出
 * @returns 
 */
 export const logout = (payload: Token) => {
    return {
        type: 'login/logout' as const,
        payload
    }
}